package com.david.mydemo.ctl_storage.service.impl;

import com.david.mydemo.ctl_storage.util.LocalStorage;
import com.david.mydemo.ctl_storage.service.IStorageService;
import com.david.mydemo.util.DateUtils;
import com.david.mydemo.util.MyResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.stream.Stream;

/**
 * 提供存储服务类，所有存储服务均由该类对外提供
 */
@Log4j2
public class StorageServiceImpl implements IStorageService {

    private String active;
    private LocalStorage localStorage;

    public String getActive() {
        return active;
    }

    public void setActive(String active) {
        this.active = active;
    }

    public LocalStorage getLocalStorage() {
        return localStorage;
    }

    public void setLocalStorage(LocalStorage localStorage) {
        this.localStorage = localStorage;
    }

    /**
     * 存储一个文件对象
     *
     * @param file   文件输入
     * @param contentLength 文件长度
     * @param contentType   文件类型
     * @param fileName      文件索引名
     */
    @Override
    public MyResponse store(MultipartFile file, long contentLength, String contentType, String fileName) {
        String key = generateKey(fileName);
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.error("获取文件流报错，错误信息：", e);
            return new MyResponse().fail("获取文件流报错");
        }
        localStorage.store(inputStream, contentLength, contentType, key);
        String url = generateUrl(key);
        log.debug("对象相关信息：name:{},size:{},type:{},key:{},url:{}", fileName, contentLength, contentType, key, url);
        return new MyResponse().success(url);
    }

    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);
        return DateUtils.dateTimeNow() + suffix;
    }

    @Override
    public Stream<Path> loadAll() {
        return localStorage.loadAll();
    }

    @Override
    public Path load(String keyName) {
        return localStorage.load(keyName);
    }

    @Override
    public Resource loadAsResource(String keyName) {
        return localStorage.loadAsResource(keyName);
    }

    @Override
    public void delete(String keyName) {
        localStorage.delete(keyName);
    }

    @Override
    public String generateUrl(String keyName) {
        return localStorage.generateUrl(keyName);
    }

    @Override
    public String downloadUrl(String keyName) {
        return localStorage.getDownload() + keyName;
    }

}
